<?php


namespace app\shop\service\user;


use app\enterprise\model\Group as GroupModel;
use app\enterprise\model\GroupUser;
use app\enterprise\model\Message;
use app\shop\common\consts\Consts;
use app\shop\model\order\OrderModel;
use app\shop\model\user\GroupUserModel;
use app\shop\model\user\UserModel;
use app\shop\service\BaseService;
use Overtrue\Pinyin\Pinyin;
use think\facade\Db;

class GroupService extends BaseService
{

    public static function getInstance()
    {
        return new GroupUserModel();
    }

    public function __construct()
    {
    }

    /**
     * 创建订单群聊
     * @param $userInfo
     * @param $orderId
     * @return bool|\think\response\Json
     */
    public static function createOrderGroup($userInfo, $orderId)
    {
        try {
            $orderInfo = OrderModel::find($orderId);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            $groupName = $orderInfo['order_name'];

            $designId = $orderInfo['design_id'];
            if (!$designId) {
                throw new \Exception('订单未指派设计师');
            }
            $salesId = $orderInfo['sale_id'];
            if (!$salesId) {
                throw new \Exception('订单未指派销售');
            }
            $salesInfo = UserModel::find($salesId);
            if (!$salesInfo) {
                throw new \Exception('销售不存在');
            }
            if ($salesInfo['role_id'] == Consts::SALE_ID) {
                $salesLeaderId = UserModel::where('department_id', $salesInfo['department_id'])
                    ->where('role_id', Consts::SALE_LEADER_ID)
                    ->value('user_id');
                if (!$salesLeaderId) {
                    throw new \Exception('销售总监不存在');
                }
            } else {
                $salesLeaderId = $salesId;
            }
            $uid = $userInfo['user_id'];
            $userIdArr = [$uid, $salesLeaderId, $designId, $orderInfo['user_id']];

            $setting = ['manage' => 0, 'invite' => 1, 'nospeak' => 0];

            $pinyin = new Pinyin();
            $groupNamePy = $pinyin->phrase($groupName, '');
            $create = [
                'create_user' => $uid,
                'owner_id' => $uid,
                'name' => $groupName,
                'name_py' => $groupNamePy,
                'setting' => json_encode($setting),
            ];
            $group = self::getInstance();
            $group->save($create);

            $groupId = $group->group_id;

            $dataAll = [];
            sort($userIdArr);
            foreach ($userIdArr as $k => $v) {
                $info = [
                    'user_id' => $v,
                    'invite_id' => $uid,
                    'status' => 1,
                    'role' => 3,
                    'group_id' => $groupId
                ];
                if ($v == $uid) {
                    $info['invite_id'] = 0;
                    $info['role'] = 1;
                }
                $dataAll[] = $info;
            }
            $groupUser = new GroupUser();
            $groupUser->saveAll($dataAll);

            $url = GroupModel::setGroupAvatar($groupId);
            $groupInfo = [
                'displayName' => $create['name'],
                'owner_id' => $create['owner_id'],
                'role' => 3,
                'name_py' => $create['name_py'],
                'id' => 'group-' . $groupId,
                'avatar' => avatarUrl($url, $create['name'], $groupId, 120),
                'is_group' => 1,
                'lastContent' => $userInfo['realname'] . ' 创建了群聊',
                'lastSendTime' => time() * 1000,
                'index' => "[2]群聊",
                'is_notice' => 1,
                'is_top' => 0,
                'setting' => $setting,

            ];
            Message::create([
                'from_user' => $uid,
                'to_user' => $groupId,
                'content' => str_encipher('创建了群聊'),
                'type' => 'event',
                'is_group' => 1,
                'is_read' => 1,
                'is_last' => 1,
                'chat_identify' => 'group-' . $groupId
            ]);
            wsSendMsg($userIdArr, 'addGroup', $groupInfo);
            return true;
        } catch (\Exception $exception) {
            return error($exception->getMessage());
        }
    }

    /**
     * 添加群成员
     * @param int $inviteUid
     * @param int $groupId
     * @param array $userIdArr
     * @return bool
     */
    public static function addGroupUser(int $inviteUid, int $groupId, array $userIdArr): bool
    {
        try {
            $dataAll = [];
            foreach ($userIdArr as $k => $v) {
                $dataAll[] = [
                    'group_id' => $groupId,
                    'user_id' => $v,
                    'role' => 3,
                    'invite_id' => $inviteUid
                ];
            }
            $groupUser = new GroupUser;
            $groupUser->saveAll($dataAll);
            $url = GroupModel::setGroupAvatar($groupId);
            wsSendMsg($groupId, "addGroupUser", ['group_id' => $groupId, 'avatar' => $url], 1);
            return true;
        } catch (\Exception $exception) {
            return error($exception->getMessage());
        }
    }
}